package com.person.mall.controller;

import com.person.mall.consts.MallConst;
import com.person.mall.form.UserRegistForm;
import com.person.mall.form.UserLoginForm;
import com.person.mall.pojo.User;
import com.person.mall.service.IUserService;
import com.person.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static com.person.mall.enums.ResponseEnum.*;

/**
 * @author 最酷的桃儿wjc
 * * @date 2022/5/14
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private IUserService iUserService;
    @PostMapping("/user/register")
    /**
     * 1.表单验证如果在后台处理就可以这么做
     * 2.注册功能
     */
    public ResponseVo registerUser(@Valid @RequestBody UserRegistForm userRegistForm, BindingResult bindingResult){
        //如果参数有误就返回参数错误状态码，和错误的字段
        if (bindingResult.hasErrors()){
            return ResponseVo.errorParam(PARAM_ERROR,bindingResult);
        }
        //使用了Spring自带的类copy，因为把表单验证的字段单独做了一个类
        User user = new User();
        BeanUtils.copyProperties(userRegistForm,user);
        return  iUserService.registerUser(user);
    }

    /**
     * 用户登录
     * @param userLoginForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/user/login")
    public ResponseVo<User> loginUser(@Valid @RequestBody
                                      UserLoginForm userLoginForm,
                                      BindingResult bindingResult,
                                      HttpSession session){
        //感觉这个很好用，如果参数有错误就可以报错
        if (bindingResult.hasErrors()){
            return ResponseVo.errorParam(PARAM_ERROR,bindingResult);
        }
        ResponseVo<User> userResponseVo = iUserService.loginUser(userLoginForm.getUsername(), userLoginForm.getPassword());
        //设置session其实这步也可以在前台进行处理
        session.setAttribute(MallConst.CURRENT_USER,userResponseVo.getData());
        return userResponseVo;
    }

    /**
     * 将用户信息从session取得当中
     * @param session
     * @return
     */
    @GetMapping("/user")
    public ResponseVo<User> userInfo(HttpSession session){
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVo.successGetData(user);
    }

    /**
     * 将用户信息从session当中移除
     * @param session
     * @return
     */
    @PostMapping("/user/logout")
    public ResponseVo logoutUser(HttpSession session){
        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success(SUCCESS);
    }

}
